import platform
from program.config import *
import matplotlib.pyplot as plt
import pandas as pd
from matplotlib import ticker as plticker
import sys

FIRST_COLUMN_NAME = 'compound_name'


def compare_parameters_plateau(df, upper_limit=500, lower_limit=0):
    df = df[(df['因子参数'] > lower_limit) & (df['因子参数'] < upper_limit)]
    columns = df.columns.to_list()
    filter_columns = []
    for column in columns:
        if column.startswith('过滤'):
            filter_columns.append(column)
    groups = df.groupby(filter_columns + [FIRST_COLUMN_NAME], dropna=False)
    fig, axs = plt.subplots(len(groups))
    fig.set_size_inches(14, 8 * len(groups))
    # set font size
    plt.rcParams.update({'font.size': 8})
    if len(filter_columns) != 0:
        group_sets = df.groupby(filter_columns, dropna=False)
        idx = 0
        for name, group_set in group_sets:
            sub_groups = group_set.groupby(FIRST_COLUMN_NAME, dropna=False)
            for compound_name, group in sub_groups:
                ax = fig.axes[idx]
                # check if group has same entity
                if len(group['因子参数'].unique()) != len(group['因子参数']):
                    print("参数平原：", compound_name, "有重复数据，请注意检查")
                ax.bar(group['因子参数'], group['累积净值'], width=3)
                # 设置x轴刻度更密集
                loc = plticker.MultipleLocator(base=20.0)
                ax.xaxis.set_major_locator(loc)
                ax.set_title(f'{compound_name}__{name}')
                idx += 1
    else:
        sub_groups = df.groupby(FIRST_COLUMN_NAME, dropna=False)
        idx = 0
        for compound_name, group in sub_groups:
            ax = fig.axes[idx]
            # check if group has same entity
            if len(group['因子参数'].unique()) != len(group['因子参数']):
                print("参数平原：", compound_name, "有重复数据，请注意检查")
            ax.bar(group['因子参数'], group['累积净值'], width=3)
            # 设置x轴刻度更密集
            loc = plticker.MultipleLocator(base=20.0)
            ax.xaxis.set_major_locator(loc)
            ax.set_title(f'{compound_name}__N/A')
            idx += 1
    save_path = os.path.join(output_path,'参数遍历结果','参数平原结果查看')
    if not os.path.exists(save_path):
        os.mkdir(save_path)
    plt.savefig(os.path.join(save_path,f'{factor_file}_{tf}.png'))


def configure_font():
    # === 绘图显示中文
    if platform.system() == 'Windows':
        # windows
        plt.rcParams['font.sans-serif'] = ['SimHei']
        plt.rcParams['axes.unicode_minus'] = False
    elif platform.system() == 'Linux':
        # Linux
        plt.rcParams['font.sans-serif'] = ['AR PL UKai CN']  # 指定默认字体
    else:
        # mac
        plt.rcParams['font.sans-serif'] = ['Arial Unicode MS']  # 指定默认字体
    plt.rcParams["axes.unicode_minus"] = False  # 处理负刻度值
    # plt.rcParams.update({'font.size': 20})


if __name__ == '__main__':
    configure_font()
    # 改成你的路径
    for factor_file in factor_name_list:
        for tf in factor_ascending:
            data = pd.read_csv(os.path.join(output_path,f"参数遍历结果/选币因子分类/['{factor_file}'].csv"),encoding='utf-8')
            data.rename(columns={'Unnamed: 0': 'compound_name'}, inplace=True)
            # 按回测区间分组
            data['compound_name'] = data['回测区间']
            # 因子TF
            data = data[data['因子TF']==tf]
            compare_parameters_plateau(data)


